//
//  MallCategoryVC.m
//  LazyCat
//
//  Created by linhui on 16/3/2.
//  Copyright (c) 2016年 zhanshu. All rights reserved.
//

#import "MallCategoryVC.h"
#import "CatecoryObject.h"
#import "CategorySubVC.h"
#import "FeWifiManHub.h"
#import "SearchViewController.h"
@interface MallCategoryVC ()<UIPageViewControllerDataSource,UIPageViewControllerDelegate,UIScrollViewDelegate,UISearchBarDelegate>
{
    UIPageViewController *_pageViewCtrl;//pageviewcontroller
    NSMutableArray *_dataArray;//专题数据源
    NSMutableArray *_dataArrayTwo;//分类数据源
    NSInteger _currentPage;//当前页
    UIScrollView *_bgView;//无数据的背景提示
    UIView *_lineView;//按钮下方滚动条
    CGFloat _btnW;//上面滚动项宽度
    UICollectionView *_collectionView;//分类视图
    UIView *_backView;//分类按钮
    UIView *_backView2;//三
    UIButton *_btn1;
    UIButton *_btn2;
    UIButton *_btn3;
    UIImageView *_priceImg;
    UIImageView *_saleImg;
    NSInteger _num1;
    NSInteger _num2;
    NSString *_sortStr;//排序类型
    FeWifiManHub *_loading;
    UISearchController *_searchController;
//    UISearchBar *_searchBar;
    UIView *_bottomView;//底部操作View
    UIView *_notesView;//无网络背景提示..
}
@property (nonatomic, strong)UIView *bottomViewEdit;
@property (nonatomic, strong)UIImageView *seleImageView;
@end

@implementation MallCategoryVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self initNav:@"公共库" doBack:YES];
    
    //搜索按钮
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(ScreenWidth - 52, 30, 42, 30);
    
    [searchBtn addTarget:self action:@selector(goSearch) forControlEvents:UIControlEventTouchUpInside];
    [searchBtn setImage:[UIImage imageNamed:@"searchLog"] forState:UIControlStateNormal];
    [searchBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    searchBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [searchBtn setImageEdgeInsets:UIEdgeInsetsMake(4, 10, 4, 10)];
    [self.navBar addSubview:searchBtn];
    [self createBottomView];
    
    /*
     
     */
    [AppData share].mallCategoryVC = self;
    
    
    /**
     搜索框
     */
//    if (!_searchBar) {
//        _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 45)];
//        _searchBar.delegate = self;
//        [self.view sendSubviewToBack:_searchBar];
//        _searchBar.placeholder = @"搜索商品名称";
//        _searchBar.showsCancelButton = NO;
//        //        _searchBar.backgroundColor = BackColor;
//        _searchBar.barTintColor = BackColor;
//        [self.view addSubview:_searchBar];
//        
//        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, 1.5)];
//        lineView.backgroundColor = [UIColor whiteColor];
//        [self.view addSubview:lineView];
//        
//        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        btn.frame = CGRectMake(0, 64, ScreenWidth, 44);
//        [btn addTarget:self action:@selector(goSearch) forControlEvents:UIControlEventTouchUpInside];
//        [self.view addSubview:btn];
//    }
    /**
     滚动条
     */
    _bgView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, 35)];
    _bgView.showsHorizontalScrollIndicator = NO;
    _bgView.backgroundColor =SetColor(248, 248, 248, 0.5);
    
    // lineView
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenWidth, 34, 1)];
    lineView.backgroundColor = SetColor(224, 224, 224, 0.5);
    [_bgView addSubview:lineView];
    
    [self.view addSubview:_bgView];
    
    _bgView.alpha = 1;
    _dataArray = [[NSMutableArray alloc]init];
    _dataArrayTwo = [[NSMutableArray alloc]init];
    [self createUI];
}

- (void)createBottomView
{
    /*
     bottomViewTwo
     
     */
    self.bottomViewEdit = [[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight - 50, ScreenWidth, 50)];
    self.bottomViewEdit.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomViewEdit];
    
    //leftView
    self.seleImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 16, 17, 17)];
    self.seleImageView.image = [UIImage imageNamed:@"btn_delete"];
    [self.bottomViewEdit addSubview:self.seleImageView];
    
    UILabel *allSeleLabel = [[UILabel alloc]initWithFrame:CGRectMake(37, 0, 63, 50)];
    allSeleLabel.font = FontSet(13);
    allSeleLabel.textAlignment = NSTextAlignmentLeft;
    allSeleLabel.text = @"全选";
    allSeleLabel.textColor = SetColor(51, 51, 51, 1);
    [self.bottomViewEdit addSubview:allSeleLabel];
    
    // bottomBtn
    NSArray *btnArr = @[@"",@"一键导入"];
    CGFloat height = 40;
    CGFloat space = 10;
    CGFloat width = (ScreenWidth - (space * 3)) / 2.0;
    for (int i = 0; i < btnArr.count; i++) {
        UIButton *bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        bottomBtn.frame = CGRectMake(space + i * (width + space), 5, 100 + i * (width - 100), height);
        [bottomBtn setTitle:btnArr[i] forState:UIControlStateNormal];
        [bottomBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bottomBtn setBackgroundColor:i == 0 ? [UIColor clearColor] : SetColor(204, 204, 204, 1)];
        bottomBtn.titleLabel.font = FontSet(16);
        bottomBtn.layer.cornerRadius = 5;
        bottomBtn.layer.masksToBounds = YES;
        [bottomBtn addTarget:self action:@selector(bottomBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        if (i == 1) {
            bottomBtn.enabled = NO;
        }
        bottomBtn.tag = 17 + i;
        [self.bottomViewEdit addSubview:bottomBtn];
    }
}

- (void)setUpNoNetView {
    _notesView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 114)];
    _notesView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_notesView];
    UIImageView *netImg = [[UIImageView alloc] initWithFrame:CGRectMake((ScreenWidth-100)/2, 70, 100, 90)];
    netImg.image = [UIImage imageNamed:@"无网络_r1_c1"];
    [_notesView addSubview:netImg];
    UILabel *netFail = [[UILabel alloc] initWithFrame:CGRectMake(0, 180, ScreenWidth, 20)];
    netFail.text = @"网络请求失败";
    netFail.textAlignment = NSTextAlignmentCenter;
    netFail.font = [UIFont systemFontOfSize:16];
    [_notesView addSubview:netFail];
    UIButton *refresh = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 109)];
    //[refresh setImage:[UIImage imageNamed:@"无网络_r3_c2 下午4.23.04"] forState:UIControlStateNormal];
    refresh.adjustsImageWhenHighlighted = NO;
    [_notesView addSubview:refresh];
    [refresh addTarget:self action:@selector(refreshV) forControlEvents:UIControlEventTouchUpInside];//刷新
}
-(void)refreshV {//刷新按钮
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        _notesView.hidden = NO;
    }else {
        _notesView.hidden = YES;
        [self createUI];
    }
}

- (void)createUI{
    if (kNetworkNotReachability) {
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        [self setUpNoNetView];
    }else {
        //加载动画
        _loading = [[FeWifiManHub alloc] initWithView:_collectionView withMode:FeWifiManHubModeOnlyLoader];
        _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 5, _loading.frame.size.width, _loading.frame.size.height);
        [self.view addSubview:_loading];
        [_loading show];
        
        //
        NSString *kUrl;
        kUrl = [NSString stringWithFormat:ProductGGK,[AppData share].username,[AppData share].username];
        NSMutableArray *Marr =[[NSMutableArray alloc]init];
        NSMutableArray *Farr=[[NSMutableArray alloc]init];
        
        [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *dic = networkRequest.responseData;
            NSArray * arr = [dic objectForKey:@"categories"];
            for (int i = 0; i < arr.count; i++) {
                [Marr addObject:[arr[i]objectForKey:@"categoryname"]];
                [Farr addObject:[arr[i]objectForKey:@"categoryid"]];
            }
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:Farr forKey:@"PID"];
            [userDefaults synchronize];
            
            //test............
            NSArray *array = Marr;
            for(int i=0;i<array.count;i++){
                CatecoryObject *tab = [[CatecoryObject alloc]init];
                tab.title = array[i];
                tab.subViewController = [[CategorySubVC alloc]init];
                tab.subViewController.currentPage = i;
                [_dataArray addObject:tab];
                __weak typeof(self)wSelf = self;
                [tab.subViewController setMyBlock:^(UIViewController *web) {
                    [wSelf.navigationController pushViewController:web animated:YES];
                }];
                
                
                [tab.subViewController setRefreshAddBtnStateBlock:^(NSInteger seleCount, BOOL isAllSele) {
                    UIButton *seleBtn = (UIButton *)[wSelf.view viewWithTag:17];
                    UIButton *addBtn = (UIButton *)[wSelf.view viewWithTag:18];
                    
                    if (seleCount > 0) {
                        if (isAllSele)
                        {
//                            seleBtn.selected = YES;
                            self.seleImageView.image = [UIImage imageNamed:@"btn_choicee"];
                        }else {
//                            seleBtn.selected = NO;
                            self.seleImageView.image = [UIImage imageNamed:@"btn_delete"];
                        }
                        addBtn.backgroundColor = MainColor;
                        addBtn.enabled = YES;
                    }else {
                        addBtn.backgroundColor = SetColor(204, 204, 204, 1);
                        addBtn.enabled = NO;
//                        seleBtn.selected = NO;
                        self.seleImageView.image = [UIImage imageNamed:@"btn_delete"];
                        
                    }
                    
                }];
            }
            _currentPage = 0;
            _lineView = [[UIView alloc]init];
            _lineView.backgroundColor = MainColorT;
            [_bgView addSubview:_lineView];
            _btnW = 0;
            for(int i=0;i<_dataArray.count;i++)
            {
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(i*70, 0, 70, 35);
                [btn setTitle:array[i] forState:UIControlStateNormal];;
                btn.backgroundColor = [UIColor orangeColor];
                [btn setTitleColor:SetColor(51, 51, 51, 1) forState:UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:13];
                //btn长度和位置计算
                CGSize size = [btn.titleLabel.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:btn.titleLabel.font,NSFontAttributeName, nil]];
                btn.frame = CGRectMake(23*(i + 1) + _btnW, 0, size.width, 35);
                _btnW += size.width;
                [btn setTitleColor:MainColorT forState:UIControlStateSelected];
                [btn setBackgroundColor:[UIColor clearColor]];
                [btn addTarget:self action:@selector(changeTab:) forControlEvents:UIControlEventTouchUpInside];
                btn.tag = 100 + i;
                [_bgView addSubview:btn];
                if(i==0){
                    btn.selected = YES;
                    _lineView.frame = CGRectMake(btn.frame.origin.x, 33, btn.size.width, 2);
                }
            }
            
            
            _bgView.contentSize =CGSizeMake(23*(_dataArray.count + 1) + _btnW, 0);
            [self configPageViewController];
        }];
    }
    _num1 = 0;
    _num2 = 0;
}

/**
 *  搜索搜索
 */
- (void)goSearch {
    SearchViewController *searchVC = [[SearchViewController alloc]init];
    
    searchVC.searchType = TypeProductsLib;
    [self.navigationController pushViewController:searchVC animated:YES];
}
#pragma mark -- 全选按钮点击事件
- (void)allSelectedBtnClick:(UIButton *)sender {
    NSString *str;
    if (sender.selected == NO) {
        sender.selected = YES;
        str = [NSString stringWithFormat:@"%d",sender.isSelected];
    }else if (sender.selected == YES){
        sender.selected = NO;
        str = [NSString stringWithFormat:@"%d",sender.isSelected];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"all_selected_BTN" object:str userInfo:nil];
}

- (void)configPageViewController{
    _pageViewCtrl = [[UIPageViewController alloc]initWithTransitionStyle:(UIPageViewControllerTransitionStyleScroll) navigationOrientation:(UIPageViewControllerNavigationOrientationHorizontal) options:nil];
    if (_currentPage < [_dataArray count]) {
        CategorySubVC * sub = [_dataArray[_currentPage] subViewController];
        [_pageViewCtrl setViewControllers:@[sub] direction:(UIPageViewControllerNavigationDirectionForward) animated:YES completion:^(BOOL finished) {
        }];
    }
    _pageViewCtrl.view.frame = CGRectMake(0, 35+64, ScreenWidth, ScreenHeight-35-64 - 50 );
    [self.view addSubview:_pageViewCtrl.view];
    _pageViewCtrl.dataSource = self;
    _pageViewCtrl.delegate = self;
    //获取显示所有view的滚动视图
    UIScrollView *sv = _pageViewCtrl.view.subviews[0];
    sv.delegate = self;
    [_pageViewCtrl.view.subviews[0] setDelegate:self];
}
//单击按钮时切换视图
- (void)changeTab:(UIButton *)sender {
    NSInteger index = sender.tag-100;
    CategorySubVC *sub = [_dataArray[index] subViewController];
    __weak typeof(_bgView)wBgView = _bgView;
    __weak typeof(_lineView)wLineView = _lineView;
    //显示翻页后要显示sub，翻页方向根据单击的按钮决定
    [_pageViewCtrl setViewControllers:@[sub] direction:_currentPage>index animated:YES completion:^(BOOL finished) {
        _currentPage = index;
        for(UIView *view in wBgView.subviews){
            if([view isKindOfClass:[UIButton class]]){
                UIButton *tb = (UIButton *)view;
                if(tb.tag == sender.tag){
                    tb.selected=YES;
                }else {
                    tb.selected = NO;
                }}}
        wLineView.frame = CGRectMake(sender.frame.origin.x, 33, sender.width, 2);
    }];
    if ((16*(_dataArray.count + 1) + _btnW) > ScreenWidth) {
        //点击按钮滚动到中间
        CGFloat offsetX = sender.center.x - 3*ScreenWidth/8;
        if (offsetX < 0) { // 处理最小滚动偏移量
            offsetX = 0;
        }
        CGFloat maxOffsetX = _bgView.contentSize.width - ScreenWidth;
        if (offsetX > maxOffsetX) { // 处理最大滚动偏移量
            offsetX = maxOffsetX;
        }
        NSLog(@"---=-=-=:%f",offsetX);
        [_bgView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    }
    
}
//返回按钮点击
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark --
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
    CategorySubVC *sub = (CategorySubVC *)viewController;
    NSInteger index = sub.currentPage;
    index++;
    if(index>=_dataArray.count){
        index = 0;
        return nil;
    }
    CategorySubVC *rsvc = [_dataArray[index]subViewController];
    return rsvc;
}
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController{
    CategorySubVC *sub = (CategorySubVC *)viewController;
    NSInteger index = sub.currentPage;
    index--;
    if(index<0){
        index = _dataArray.count-1;
        return nil;
    }
    CategorySubVC *rsvc = [_dataArray[index]subViewController];
    return rsvc;
    
}
//翻页成功后执行的方法
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed{
    CategorySubVC *sub = (CategorySubVC *)pageViewController.viewControllers[0];
    _currentPage = sub.currentPage;
    for(UIView *view in _bgView.subviews){
        if([view isKindOfClass:[UIButton class]]){
            UIButton *btn = (UIButton *)view;
            if(btn.tag-100==_currentPage){
                btn.selected =YES;
            }else {
                btn.selected = NO;
            }
        }
    }
    UIButton *btn = (UIButton *)[_bgView viewWithTag:_currentPage + 100];
    _lineView.frame = CGRectMake(btn.frame.origin.x, 33, btn.width, 2);
    if ((16*(_dataArray.count + 1) + _btnW) > ScreenWidth) {
        //点击按钮滚动到中间
        CGFloat offsetX = btn.center.x - 3*ScreenWidth/8;
        if (offsetX < 0) { // 处理最小滚动偏移量
            offsetX = 0;
        }
        CGFloat maxOffsetX = _bgView.contentSize.width - ScreenWidth;
        if (offsetX > maxOffsetX) { // 处理最大滚动偏移量
            offsetX = maxOffsetX;
        }
        [_bgView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    }
}

- (void)noNetBtnClick {
    if (kNetworkNotReachability) {
        //NSLog(@".....");
    }else {
        [self createUI];
    }
}
#pragma mark - UISearchControllerDelegate代理方法
- (void)didDismissSearchController:(UISearchController *)searchController {
    if (searchController.searchBar.text.length == 0) {
        return;
    }
}
#pragma mark - UISearchBarDelegate代理方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    return YES;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    //    SearchViewController *searchVC = [[SearchViewController alloc]init];
    //    [self.navigationController pushViewController:searchVC animated:YES];
    //    [searchBar endEditing:YES];
}
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar {
    
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchText.length == 0) {
        return;
    }
    
    //[self.resultProvinces removeAllObjects];
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
}
- (void)bottomBtnClicked:(UIButton *)sender
{
    if (sender.tag == 17) { // 全选
        if (!sender.selected) {
            sender.selected = YES;
            self.seleImageView.image = [UIImage imageNamed:@"btn_choicee"];
            if (self.allSelectedBlock) {
                self.allSelectedBlock(@"1");
            }
        }else {
            sender.selected = NO;
            self.seleImageView.image = [UIImage imageNamed:@"btn_delete"];
            if (self.allSelectedBlock) {
                self.allSelectedBlock(@"0");
            }
        }
        
    }else if (sender.tag == 18) {
        if (self.allSelectedBlock) {
            self.allSelectedBlock(@"2");
        }
    }
}

- (void)dealloc {
    
}
@end
